<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>中文姓名：<el-input placeholder="请输入内容" v-model="selectForm.chineseName" clearable class="dzy-custom-input"></el-input></div>
            <div>
              性别：
              <el-select v-model="selectForm.gender" clearable placeholder="请选择">
                <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>&nbsp;
            </div>
            <div>证件号码：<el-input placeholder="请输入内容" v-model="selectForm.credentialsNumber" clearable class="dzy-custom-input"></el-input></div>
            <div>出生日期：
              <el-date-picker
                v-model="selectForm.birthday"
                type="date"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
              </el-date-picker>
            </div>
            <div>来华目的：
              <el-select v-model="selectForm.purposeToChina" filterable clearable placeholder="请选择">
                <el-option v-for="(item,index) in purposeToChinaOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            class="custom-dialog_style" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     :disabled="showOnly"
                     ref="formData">
              <el-form-item label="外文姓：" prop="lastName">
                <el-input v-model="formData.lastName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="外文名：" prop="firstName">
                <el-input v-model="formData.firstName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="中文姓名：">
                <el-input v-model="formData.chineseName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="gender">
                <el-select v-model="formData.gender" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期：" prop="birthday">
                <div class="block">
                  <el-date-picker
                    v-model="formData.birthday"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期时间"
                    :picker-options="dataPickerBeforeTodayOptions">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="国籍：" prop="nationality">
                <el-select v-model="formData.nationality" autocomplete="off" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in nationalityOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="宗教信仰：">
                <el-select v-model="formData.religion" autocomplete="off" filterable clearable placeholder="请选择">
                  <el-option v-for="(item,index) in religionOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="证件代码：" prop="credentialsCode">
                <el-select v-model="formData.credentialsCode" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in credentialsCodeOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="证件号码：" prop="credentialsNumber">
                <el-input v-model="formData.credentialsNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="证件有效期：" prop="validityDocuments">
                <div class="block">
                  <el-date-picker
                    v-model="formData.validityDocuments"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="联系方式：" prop="phone">
                <el-input v-model="formData.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="来华目的：" prop="purposeToChina">
                <el-select v-model="formData.purposeToChina" filterable clearable placeholder="请选择">
                  <el-option v-for="(item,index) in purposeToChinaOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业类别：">
                <el-select v-model="formData.careerCategory" filterable clearable placeholder="请选择">
                  <el-option v-for="(item,index) in careerCategoryOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业：">
                <el-input v-model="formData.career" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="服务处所：">
                <el-input v-model="formData.servicePlace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="抵达日期：" prop="arrivalDate">
                <div class="block">
                  <el-date-picker
                    v-model="formData.arrivalDate"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期时间"
                    :picker-options="dataPickerBeforeTodayOptions">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="预计离开日期：" prop="leaveDate">
                <div class="block">
                  <el-date-picker
                    v-model="formData.leaveDate"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="是否重点关注人员：">
                <el-select v-model="formData.focusStatus" clearable placeholder="请选择">
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="现住地：" prop="currentAddr">
                <el-input v-model="formData.currentAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="现住门(楼)详址：" prop="currentAddrDetail">
                <el-input v-model="formData.currentAddrDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="网格：" prop="gridIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    :props="gridIdProps"
                    :show-all-levels="false"
                    clearable @change="afterGridIdCheck"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="现居住地类型：">
                <el-radio-group v-model="livePlaceType" size="medium" @change="placeTypeChangedEvt">
                  <el-radio-button label="小区" ></el-radio-button>
                  <el-radio-button label="院落"></el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="院落：" v-if="isYardSelectShow">
                <el-select v-model="formData.courtyardId" clearable filterable placeholder="请选择">
                  <el-option v-for="(yard,index) in yardOptions" :key="index" :label="yard.courtyardNo" :value="yard.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="小区：" v-if="isCommunitySelectShow">
                <el-select v-model="formData.communityId" filterable clearable placeholder="请选择" @change="afterCommunityIdCheck">
                  <el-option v-for="(community,index) in communityOptions" :key="index" :label="community.name" :value="community.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="楼栋：" v-if="isCommunitySelectShow">
                <el-select v-model="formData.buildingId" filterable clearable placeholder="请选择" @change="afterBuildIdCheck">
                  <el-option v-for="(build,index) in buildingOptions" :key="index" :label="build.buildingName" :value="build.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="单元：" v-if="isCommunitySelectShow">
                <el-select v-model="formData.unitId" filterable clearable placeholder="请选择" @change="afterUnitIdCheck">
                  <el-option v-for="(unit,index) in unitOptions" :key="index" :label="unit.unitName" :value="unit.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="房屋：" v-if="isCommunitySelectShow">
                <el-select v-model="formData.houseId" filterable clearable placeholder="请选择">
                  <el-option v-for="(house,index) in houseOptions" :key="index" :label="house.houseNumber" :value="house.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion} from '@/utils/region'
import {validatePhone} from '@/utils/validate'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findCommunityList, findBuildingList, findUnitList, findHouseList, getHouse, findCourtyardList} from '@/http/FangWuGuanLiApi'
import {findOverseasPerson, updateOverseasPerson, delOverseasPerson, createOverseasPerson, getOverseasPerson} from '@/http/PopulationApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: false,
      treeData: [],
      pageData: {},
      selectForm: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      formData: {},
      tableColumns: [
        { prop: 'chineseName', label: '中文姓名', width: '100' },
        { prop: 'gender', label: '性别', formatter: this.genderFormatter, width: '50' },
        { prop: 'birthday', label: '出生日期', formatter: this.dateFormatter },
        { prop: 'nationality', label: '国籍（地区）', formatter: this.nationalityFormatter },
        { prop: 'credentialsCode', label: '证件代码', formatter: this.codeFormatter, width: '120' },
        { prop: 'credentialsNumber', label: '证件号码' },
        { prop: 'validityDocuments', label: '证件有效期', formatter: this.dateFormatter },
        { prop: 'phone', label: '联系方式' }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      communityOptions: [],
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      gridIdProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      rules: {
        lastName: [
          { required: true, message: '请输入外文姓', trigger: 'blur' }
        ],
        firstName: [
          { required: true, message: '请输入外文名', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择出生日期', trigger: 'blur' }
        ],
        credentialsNumber: [
          { required: true, message: '请输入证件号', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        nationality: [
          { required: true, message: '请输入国籍', trigger: 'blur' }
        ],
        credentialsCode: [
          { required: true, message: '请选择证件代码', trigger: 'blur' }
        ],
        validityDocuments: [
          { required: true, message: '请选择证件有效期', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        purposeToChina: [
          { required: true, message: '请选择来华目的', trigger: 'blur' }
        ],
        currentAddr: [
          { required: true, message: '请输入现住地', trigger: 'blur' }
        ],
        currentAddrDetail: [
          { required: true, message: '请输入现住门（楼）详址', trigger: 'blur' }
        ],
        arrivalDate: [
          { required: true, message: '请选择抵达日期', trigger: 'blur' }
        ],
        leaveDate: [
          { required: true, message: '请选择预计离开日期', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择网格', trigger: 'blur' }
        ]
      },
      genderOption: [],
      nationalityOption: [],
      religionOption: [],
      credentialsCodeOption: [],
      purposeToChinaOption: [],
      careerCategoryOption: [],
      livePlaceType: '小区',
      isYardSelectShow: false,
      isCommunitySelectShow: true,
      yardOptions: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.genderOption = getDictDataOption('性别')
    this.purposeToChinaOption = getDictDataOption('来华目的')
    this.getTableData()
    this.getTreeData()
  },
  methods: {
    placeTypeChangedEvt (val) {
      if (val) {
        let m = this
        const getPlaceType = {
          '小区': function () {
            m.isYardSelectShow = false
            m.isCommunitySelectShow = true
          },
          '院落': function () {
            if (m.yardOptions.length === 0 && m.formData.gridId && m.formData.gridId !== '') {
              m.getCourtyardList({likeAllGridId: m.formData.gridId})
            }
            m.isYardSelectShow = true
            m.isCommunitySelectShow = false
          }
        }
        getPlaceType[val]()
      }
    },
    getCourtyardList (param) {
      let m = this
      findCourtyardList(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            m.yardOptions = data
          }
        } else {
          return ''
        }
      })
    },
    // 格式化时间戳
    dateFormatter (row, column) {
      let prop = column.property
      if (row[prop] && row[prop] === '') return ''
      let resTime = JSON.parse(row[prop])
      return this.$moment(resTime).format('YYYY-MM-DD')
    },
    // 格式化性别
    genderFormatter (row, column) {
      let genderOption = getDictDataOption('性别')
      let resGender = ''
      for (let i = 0; i < genderOption.length; i++) {
        if (genderOption[i].code === row.gender) {
          resGender = genderOption[i].name
          break
        }
      }
      return resGender
    },
    // 格式化证件代码
    codeFormatter (row, column) {
      if (row && row.credentialsCode) {
        let credentialsCode = row.credentialsCode === '111' ? '身份证' : '护照'
        return credentialsCode
      }
    },
    // 格式化国籍
    nationalityFormatter (row, column) {
      let nationalityOption = getDictDataOption('国家和地区')
      let resNationality = ''
      for (let i = 0; i < nationalityOption.length; i++) {
        if (nationalityOption[i].code === row.nationality) {
          resNationality = nationalityOption[i].name
          break
        }
      }
      return resNationality
    },
    afterGridIdCheck (gridId) {
      if (gridId && gridId !== '') {
        this.getCourtyardList({likeAllGridId: gridId})
        findCommunityList({likeAllGridId: gridId}).then(resp => {
          if (resp.code && resp.code === '200') {
            this.communityOptions = resp.data
          } else {
            return ''
          }
        })
      } else {
        if (this.formData.gridIdArr && this.formData.gridIdArr.length > 0) {
          let gridArr = this.formData.gridIdArr
          if (gridArr.length > 0) {
            let len = gridArr.length - 1
            let param = {
              likeAllGridId: gridArr[len]
            }
            this.getCourtyardList(param)
            findCommunityList(param).then(resp => {
              if (resp.code && resp.code === '200') {
                this.communityOptions = resp.data
              } else {
                return ''
              }
            })
          }
        } else {
          this.$set(this.formData, 'courtyardId', '')
          this.$set(this.formData, 'communityId', '')
          this.$set(this.formData, 'buildingId', '')
          this.$set(this.formData, 'unitId', '')
          this.$set(this.formData, 'houseId', '')
        }
      }
    },
    afterCommunityIdCheck (val) {
      if (val) {
        let param = {communityId: val}
        findBuildingList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            this.buildingOptions = resp.data
          } else {
            return ''
          }
        })
      }
    },
    afterBuildIdCheck (val) {
      if (val) {
        let param = {buildingId: val}
        findUnitList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            this.unitOptions = resp.data
          } else {
            return ''
          }
        })
      }
    },
    afterUnitIdCheck (val) {
      if (val) {
        let param = {unitId: val}
        findHouseList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            this.houseOptions = resp.data
          } else {
            return ''
          }
        })
      }
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.gridIdArr && this.formData.gridIdArr.length !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.allGridId = getAllRegion(data)
          } else {
            this.formData.allGridId = ''
          }
          if (this.formData.id) {
            updateOverseasPerson(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              }
            })
          } else {
            createOverseasPerson(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delOverseasPerson(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      findOverseasPerson(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        this.nationalityOption = getDictDataOption('国家和地区')
        this.religionOption = getDictDataOption('宗教信仰')
        this.credentialsCodeOption = getDictDataOption('证件代码')
        this.careerCategoryOption = getDictDataOption('职业分类')
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
          this.showOnly = callbackData.sohwOnly
          this.dialogTitle = callbackData.dialogTitle
          this.dialogFormVisible = true
        } else {
          let _this = this
          getOverseasPerson(callbackData.rows[0].id).then(resp => {
            if (resp.code && resp.code === '200') {
              let obj = JSON.stringify(resp.data)
              _this.formData = JSON.parse(obj)
              _this.isYardSelectShow = !!_this.formData.courtyardId && _this.formData.courtyardId !== ''
              _this.isCommunitySelectShow = !_this.isYardSelectShow
              if (_this.formData.houseId) {
                let houseId = _this.formData.houseId
                getHouse(houseId).then(resp => {
                  if (resp.code && resp.code === '200') {
                    _this.afterCommunityIdCheck(resp.data.communityId)
                    _this.afterBuildIdCheck(resp.data.buildingId)
                    _this.afterUnitIdCheck(resp.data.unitId)
                    _this.afterGridIdCheck(resp.data.gridId)
                    _this.$set(_this.formData, 'unitId', resp.data.unitId)
                    _this.$set(_this.formData, 'buildingId', resp.data.buildingId)
                    _this.$set(_this.formData, 'communityId', resp.data.communityId)
                  }
                })
              }
              let gridnData = {}
              gridnData.id = _this.formData.gridId
              gridnData.items = _this.treeData
              let gridIdArr = getAllRegion(gridnData)
              _this.$set(_this.formData, 'gridIdArr', gridIdArr)
              _this.showOnly = callbackData.sohwOnly
              _this.dialogTitle = callbackData.dialogTitle
              _this.dialogFormVisible = true
            }
          })
        }
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.afterGridIdCheck(data.id)
      this.selectForm.likeAllGridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
